package com.neu.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.neu.pojo.ResultJson;
import com.neu.pojo.User;
import com.neu.service.UserService;

@RestController
@RequestMapping("/users")
public class UserController {
	// 代码编写处
	@Autowired
	private UserService userService;

	// 查找详情
	@GetMapping("/{id}")
	public ResultJson findUserById(@PathVariable String id) {
		User user = userService.findUserById(id);
		if (user == null) {
			return new ResultJson(500, "数据操作失败");
		} else {
			return new ResultJson(userService.findUserById(id));
		}
	}

	// 根据输入的userName模糊查找用户列表
	@GetMapping
	public ResultJson findAllUser(@RequestParam(required = false) String userName) {
		return new ResultJson(userService.findAllUser(userName));
	}

	// 插入用户
	@PostMapping
	public ResultJson insertUser(User user) {
		if (StringUtils.isAnyEmpty(user.getUserName(), user.getPassword())) {
			return new ResultJson(500, "数据操作失败");
		}
		// 查找同名账户
		User _user = userService.checkUserExists(user);
		if (_user != null) {
			return new ResultJson(500, "数据操作失败");
		}
		if (userService.insertUser(user) > 0) {
			// 添加用户成功
			return new ResultJson(null);
		} else {
			return new ResultJson(500, "数据操作失败");
		}
	}

	// 修改用户
	@PutMapping
	public ResultJson updateUser(User user) {
		if (StringUtils.isAnyEmpty(user.getId(), user.getUserName(), user.getPassword())) {
			return new ResultJson(500, "数据操作失败");
		}
		// 检测用户帐号是否重名
		if (userService.checkUserNameExists(user)>0) {
			return new ResultJson(500, "数据操作失败");
		}
		// 不重名，开赛修改，并返回结果
		if (userService.updateUser(user) > 0) {
			return new ResultJson(null);
		} else {
			return new ResultJson(500, "数据操作失败");
		}
	}

	@DeleteMapping("/{id}")
	public ResultJson deleteUserById(@PathVariable String id) {
		if (userService.deleteUser(id) > 0) {
			return new ResultJson(null);
		} else {
			return new ResultJson(500, "数据操作失败");
		}
	}
}
